package com.zwr.normal.sharemodel.aba;

import java.util.concurrent.atomic.AtomicStampedReference;

public class ABADeal {
    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A",0);

    public static void main(String[] args) throws Exception {
        System.out.println("main start ... ");

        String pre = ref.getReference();
        int stamp = ref.getStamp();

        other();
        Thread.sleep(2000);

        System.out.println("main continue...");

        boolean c = ref.compareAndSet(pre, "C", stamp, stamp + 1);
        System.out.println("交换成功：" + c);
        String next = ref.getReference();
        System.out.println(pre+"--->"+next);
    }

    private static void other() throws InterruptedException {
        new Thread(()->{
            String pre = ref.getReference();
            ref.compareAndSet(ref.getReference(),"B",ref.getStamp(), ref.getStamp()+1);
            String next = ref.getReference();
            System.out.println(pre+"--->"+next);
        }).start();

        Thread.sleep(1000);

        new Thread(()->{
            String pre = ref.getReference();
            ref.compareAndSet(pre,"A",ref.getStamp(), ref.getStamp()+1);
            String next = ref.getReference();
            System.out.println(pre+"--->"+next);
        }).start();
    }
}
